package udp_;

import org.junit.Test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UdpTest1 {

    @Test
    public void send() throws Exception {
        // 直接创建Socket对象
        DatagramSocket ds = new DatagramSocket();

        // public DatagramPacket(byte[] buf,int length,InetAddress address,int port)
        Scanner sc = new Scanner(System.in);
        String msg = sc.next();
        byte[] bys = msg.getBytes();
        // 创建发送的数据包, 包含了数据和ip以及端口信息
        DatagramPacket dp = new DatagramPacket(bys, bys.length,
                InetAddress.getLocalHost(), 9999);

        ds.send(dp);

        // 关闭资源
        ds.close();


    }

    @Test
    public void receive() throws Exception {
        // 创建Socket对象
        DatagramSocket ds = new DatagramSocket(9999);

        byte[] bys = new byte[1024];
        // public DatagramPacket(byte[] buf,int length)
        DatagramPacket dp = new DatagramPacket(bys, bys.length);

        // 接收发送端发送的数据
        ds.receive(dp);

        // 以字节数据的形式获取发送端发送的数据
        bys = dp.getData();
        // 获取数组填充字节长度
        int length = dp.getLength();
        String result = new String(bys, 0, length);
        System.out.println(result);

        // 关闭资源
        ds.close();

    }
}
